﻿namespace System.IO

open System
open System.Threading

type FileLock(path, ?readonly) =
    let readonly =
        match readonly with
        | Some(value) -> value
        | None -> true
    let writer = not readonly
    let mutable stream = 
        new FileStream(path, FileMode.Open, (if writer then FileAccess.Write else FileAccess.Read),
         if writer then FileShare.None else FileShare.Read)
    
    // <remarks>
    // This method is thread-safe.
    // </remarks>
    interface IDisposable with
        member this.Dispose() =
            let was = Interlocked.Exchange(ref stream, null)
            if was <> null then
                was.Dispose()
